# Scikit-learn的核心API设计原则
# 1. 一致性接口：所有算法都遵循相同的fit/predict模式
# 2. 模块化设计：每个算法都是一个独立的类
# 3. 丰富的数据预处理工具

from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error, r2_score

# 加载数据
diabetes = load_diabetes()
X, y = diabetes.data, diabetes.target

# 分割数据
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 数据标准化
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# 创建多个模型
models = {
    '线性回归': LinearRegression(),
    '随机森林': RandomForestRegressor(n_estimators=100, random_state=42),
    '支持向量机': SVR(kernel='rbf')
}

# 训练和评估模型
results = {}
for name, model in models.items():
    # 对于SVM使用标准化数据
    if name == '支持向量机':
        model.fit(X_train_scaled, y_train)
        y_pred = model.predict(X_test_scaled)
    else:
        model.fit(X_train, y_train)
        y_pred = model.predict(X_test)
    
    # 计算评估指标
    mse = mean_squared_error(y_test, y_pred)
    r2 = r2_score(y_test, y_pred)
    
    results[name] = {'MSE': mse, 'R2': r2}
    print(f"{name}:")
    print(f"  均方误差: {mse:.2f}")
    print(f"  决定系数: {r2:.3f}")
    print()

# 可视化模型比较
model_names = list(results.keys())
mse_values = [results[name]['MSE'] for name in model_names]
r2_values = [results[name]['R2'] for name in model_names]

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

# MSE比较
ax1.bar(model_names, mse_values, color=['blue', 'green', 'red'])
ax1.set_title('均方误差比较')
ax1.set_ylabel('MSE')
ax1.tick_params(axis='x', rotation=45)

# R2比较
ax2.bar(model_names, r2_values, color=['blue', 'green', 'red'])
ax2.set_title('决定系数比较')
ax2.set_ylabel('R²')
ax2.tick_params(axis='x', rotation=45)

plt.tight_layout()
plt.show()